﻿// 2023/3/20: 首个版本
// 2023/3/20: 优化对话框高度
// 2023/4/18: 针对中文环境优化对话框高度
// 2023/9/12: 修正英文日期显示
// 2023/9/22: 使用PassParent给ShowDialog传参
// 2023/9/25: 改为直接输入Icon对象
// 2024/6/25: 支持API3
// 2024/12/3: 使用App.ShowSelectFolderDialog
// 2025/1/9: 支持客户端模式
// 2025/1/10: 修正客户端模式下选择文件夹取消异常
// 2025/5/16: 扩大高度

using System;
using System.IO;
using System.Xml;
using ASEva;
using ASEva.Samples;
using ASEva.Utility;
using ASEva.UIEto;
using Eto.Forms;
using Eto.Drawing;

namespace CommonSource
{
    class SingleSessionPicker : DialogPanel
    {
        public SingleSessionPicker(object caller, SessionIdentifier session, Icon icon = null)
        {
            this.caller = caller;
            this.session = session;

            Icon = icon;
            Title = chinese ? "数据截取工具" : "Session Picker";
            SetFixMode(600, 470, true);

            var mainLayout = this.SetContentAsColumnLayout();
            var tableLayout = mainLayout.AddTableLayout();
            commonOptions = mainLayout.AddControl(new CommonPickOptionsControl(true), true);
            var pickIDLayout = mainLayout.AddRowLayout();
            var rangeLayout = mainLayout.AddRowLayout();

            var row = tableLayout.AddRow();
            row.AddLabel(chinese ? "源数据片段：" : "Source Session:");
            row.AddLabel(session.ToDateTime().ToString(chinese ? "yyyy/MM/dd HH:mm:ss" : "MM/dd/yyyy HH:mm:ss"));

            row = tableLayout.AddRow();
            row.AddLabel(chinese ? "输出路径：" : "Output path:");
            linkPath = row.AddLinkButton(chinese ? "(未配置)" : "(Not configured)");
            linkPath.TextColor = Colors.Red;

            pickIDLayout.AddLabel(chinese ? "截取ID：" : "Pick ID:", TextAlignment.Left, false, 75);
            textPickID = pickIDLayout.AddControl(new TextBox{ Text = defaultPickID }, true);

            rangeLayout.AddLabel(chinese ? "起始位置：" : "Pick from:", TextAlignment.Left, false, 75);
            numStart = rangeLayout.AddControl(new NumericStepper());
            rangeLayout.AddSpace();
            rangeLayout.AddLabel(chinese ? "截取长度：" : "Pick length:");
            numLength = rangeLayout.AddControl(new NumericStepper());
            rangeLayout.AddSpace();
            buttonPick = rangeLayout.AddButton(chinese ? "截取" : "Pick", false, 80);
            buttonPick.Enabled = false;

            initialize();
        }

        private async void initialize()
        {
            if (AgencyLocal.ClientSide)
            {
                var sessionLength = await AgencyAsync.GetSessionLength(session);
                if (sessionLength == null)
                {
                    delayShow(chinese ? "加载session信息失败。" : "Failed to load the session's information.");
                    return;
                }
                length = sessionLength.Value;
            }
            else
            {
                var sessionPath = AgencyLocal.GetSessionPath(session);
                var meta = sessionPath == null ? null : SessionMeta.Load(sessionPath + System.IO.Path.DirectorySeparatorChar + "meta.xml");
                if (meta == null || meta.Length == null)
                {
                    delayShow(chinese ? "加载session信息失败。" : "Failed to load the session's information.");
                    return;
                }
                length = meta.Length.Value;
            }

            if (length <= 5)
            {
                delayShow(chinese ? "Session长度太短，无法截取。" : "The session is too short to pick.");
                return;
            }

            numStart.MinValue = 0;
            numStart.MaxValue = length - 5;
            numStart.Value = 0;
            numLength.MinValue = 5;
            numLength.MaxValue = length;
            numLength.Value = 5;

            linkPath.Click += async delegate
            {
                String selected = null;
                if (AgencyLocal.ClientSide)
                {
                    await AgencyAsync.RunConsole(caller, "select-folder.consoleworkflow");
                    selected = await AgencyAsync.GetGlobalVariable("Console.SelectFolderResult", null);
                }
                else
                {
                    selected = await App.ShowSelectFolderDialog(this, chinese ? "请选择输出文件夹路径" : "Please choose the output path");
                }
                if (String.IsNullOrEmpty(selected)) return;

                linkPath.Text = selected;
                linkPath.TextColor = Colors.Green;
                buttonPick.Enabled = true;
            };

            numStart.ValueChanged += delegate
            {
                numLength.MaxValue = length - (double)numStart.Value;
            };

            textPickID.TextChanged += delegate
            {
                if (textPickID.Text.Length == 0) textPickID.Text = defaultPickID;
            };

            buttonPick.Click += async delegate
            {
                String dataPath = null;
                if (AgencyLocal.ClientSide)
                {
                    dataPath = await AgencyAsync.GetGlobalParameter("System.DataPath", null);
                }
                else
                {
                    dataPath = AgencyLocal.GetDataPath();
                }

                var targetPath = linkPath.Text;
                if (dataPath != null && targetPath.IndexOf(dataPath + Path.DirectorySeparatorChar) >= 0)
                {
                    await AgencyLocal.PopupError(chinese ? "截取数据不能存储在当前数据文件夹内。" : "Picked data can't be saved inside current data path.");
                    return;
                }

                var pickConfig = new PickConfig();
                pickConfig.PickID = textPickID.Text.Length == 0 ? defaultPickID : textPickID.Text;
                pickConfig.Options = commonOptions.Options;

                var pick = new SingleSessionPick();
                pick.SourceSessionID = session;
                pick.SourceBeginTime = numStart.Value;
                pick.SourcePickLength = numLength.Value;

                var dstSessionID = session.ToDateTime().AddSeconds((int)pick.SourceBeginTime);
                pick.DstSessionPath = targetPath + Path.DirectorySeparatorChar + dstSessionID.ToString("yyyyMMdd-HH-mm-ss");

                if (!AgencyLocal.ClientSide)
                {
                    pick.SourceSessionPath = AgencyLocal.GetSessionPath(session);

                    pick.SourceSubSessionPaths = new String[4];
                    var subPaths = AgencyLocal.GetSubDataPaths();
                    if (pick.SourceSessionPath.Length > dataPath.Length)
                    {
                        var childPath = pick.SourceSessionPath.Substring(dataPath.Length + 1);
                        for (int i = 0; i < 4; i++)
                        {
                            if (i < subPaths.Length && subPaths[i] != null) pick.SourceSubSessionPaths[i] = subPaths[i] + Path.DirectorySeparatorChar + childPath;
                        }
                    }
                }

                pickConfig.Picks.Add(pick);

                if ((await AgencyAsync.RunStandaloneTask(caller, "pick-session.system", pickConfig.ToXmlString())).Item1 == TaskResult.RunOK)
                {
                    await AgencyLocal.PopupNotice(chinese ? "Session截取成功。" : "Session picking finished.");
                    Close();
                }
            };
        }

        private void delayShow(String msg)
        {
            showTimer = new UITimer();
            showTimer.Interval = 0.1;
            showTimer.Elapsed += async delegate
            {
                showTimer.Stop();
                showTimer = null;
                await AgencyLocal.PopupError(msg);
                Close();
            };
            showTimer.Start();
        }

        private object caller;
        private SessionIdentifier session;
        private double length;
        private String defaultPickID = "pick-" + DateTime.Now.ToString("yyyyMMddHHmmss");
        private UITimer showTimer;
        private LinkButton linkPath;
        private CommonPickOptionsControl commonOptions;
        private NumericStepper numStart, numLength;
        private TextBox textPickID;
        private Button buttonPick;
        private bool chinese = AgencyLocal.GetAppLanguage() == Language.Chinese;
    }
}